package leetcode.exercise;

import java.util.HashMap;
import java.util.Map;

/*
 * @Author: guqy
 * @Description:
 *      Given an array of integers, return indices of the two numbers such that they add up to a specific target.
 *      You may assume that each input would have exactly one solution, and you may not use the same element twice.
 *  Example:
 *      Given nums = [2, 7, 11, 15], target = 9,
 *      Because nums[0] + nums[1] = 2 + 7 = 9,
 *      return [0, 1].
 * @Date 13:51 2018/3/14
 * @param null
 * @return 
 */
public class TwoSumDemo {
    public static void main(String[] args) {
        int[] nums = {10,20,30,40,50};
        int target = 80;
        int[] result = towSum2(nums,target);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result[i]);
        }

    }

    /**
     * Time complexity o(n2),Space complexity : O(1)
     * @param nums
     * @param target
     * @return int[]
     */
    public static int[] twoSum1(int[] nums, int target) {
        if(nums == null){
            return null;
        }
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }

    /**
     * Time complexity o(n),Space complexity : O(n)
     * @param nums
     * @param target
     * @return int[]
     */
    public static int[] towSum2(int[] nums,int target){
        if(nums == null){
            return null;
        }
        int len = nums.length;
        Map<Integer,Integer> integerMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < len; i++) {
            integerMap.put(nums[i],i);
        }
        for (int i = 0; i < len; i++) {
            if(integerMap.containsKey(target - nums[i]) && integerMap.get(target - nums[i]) != i){
                return new int[]{i, integerMap.get(target - nums[i])};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
